﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.AspNet.Identity;
using ezCloud.Api.Repository;
using ezCloud.Api.Models;
using System.Threading.Tasks;
using System.Web;
using System.IO;
using System.Drawing;
using System.Configuration;
using ezCloud.Api.Common;

namespace ezCloud.Api.Controllers
{
    [Authorize]
    [RoutePrefix("api/File")]
    public class FileController : ezController
    {
        //private IFileManagerService _fileManager;
        private IFlowJsRepo _flowJs;

        public FileController()
        {
            //_fileManager = new FileManagerService();
            _flowJs = new FlowJsRepo();
        }

        string Folder = HttpContext.Current.Server.MapPath(@"~/App_Data/Tmp/FileUploads").ToString();

        [HttpGet]
        [Route("Upload")]
        public async Task<IHttpActionResult> PictureUploadGet()
        {
            var request = HttpContext.Current.Request;

            var chunkExists = _flowJs.ChunkExists(Folder, request);
            if (chunkExists) return Ok();
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NoContent));
        }

        [HttpPost]
        [Route("Upload")]
        public async Task<IHttpActionResult> PictureUploadPost()
        {
            var request = HttpContext.Current.Request;
            var userFolder = HttpContext.Current.Server.MapPath("/Uploads/" +  User.Identity.GetUserId());
            if (!Directory.Exists(userFolder))
                Directory.CreateDirectory(userFolder);
            var validationRules = new FlowValidationRules();
            validationRules.AcceptedExtensions.AddRange(new List<string> { "jpeg", "jpg", "png", "bmp" });
            validationRules.MaxFileSize = 500000;

            try
            {
                var status = _flowJs.PostChunk(request, userFolder, validationRules);
    
                if (status.Status == PostChunkStatus.Done)
                {
                    // file uploade is complete. Below is an example of further file handling
                    var filePath = Path.Combine(userFolder, status.FileName);
                    var image = Image.FromFile(filePath);
                    int thumbWidth = ConfigurationManager.AppSettings["thumbnailWidth"] == null ? 320 : Int32.Parse(ConfigurationManager.AppSettings["thumbnailWidth"]);
                    int thumbHeight = ConfigurationManager.AppSettings["thumbHeight"] == null ? 480 : Int32.Parse(ConfigurationManager.AppSettings["thumbHeight"]);

                    thumbHeight = thumbWidth * image.Height / image.Width;
                    Image thumb = image.GetThumbnailImage(thumbWidth, thumbHeight, () => false, IntPtr.Zero);
                    if (!Directory.Exists(userFolder + "\\thumbnail"))
                        Directory.CreateDirectory(userFolder + "\\thumbnail");
                    thumb.Save(userFolder + "\\thumbnail\\" + thumbWidth + "_" + thumbHeight + "_" + status.FileName);

                    /*var file = File.ReadAllBytes(filePath);
                    var picture = await _fileManager.UploadPictureToS3(User.Identity.GetUserId(), file, status.FileName);*/

                    //File.Delete(filePath);
                    return Ok(new { url = Common.Utilities.FullyQualifiedApplicationPath + "Uploads/" +  User.Identity.GetUserId() + "/" + status.FileName,serverPath = "/Uploads/" +  User.Identity.GetUserId() + "/" + status.FileName});
                }
    
                if (status.Status == PostChunkStatus.PartlyDone)
                {
                    return Ok();
                }
    
                status.ErrorMessages.ForEach(x => ModelState.AddModelError("file", x));
                return BadRequest(ModelState);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("file", "exception " + ex.Message);
                return BadRequest(ModelState);
            }
        }
    }
}
